function varargout = main(varargin)

% MAIN MATLAB code for main.fig
%      MAIN, by itself, creates a new MAIN or raises the existing
%      singleton*.
%
%      H = MAIN returns the handle to a new MAIN or the handle to
%      the existing singleton*.
%
%      MAIN('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in MAIN.M with the given input arguments.
%
%      MAIN('Property','Value',...) creates a new MAIN or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before main_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to main_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help main

% Last Modified by GUIDE v2.5 05-Feb-2015 10:17:13

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @main_OpeningFcn, ...
                   'gui_OutputFcn',  @main_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before main is made visible.
function main_OpeningFcn(hObject, eventdata, handles, varargin)
    handles.output = hObject;
   
   defines = load_defined_parametrs();
   if evalin('base','exist(''direction'',''var'')')
       direction =  evalin('base','direction');
       if isequal(direction, 'Substrate')
           defines.isSubstrateDirection = 'true';
       elseif isequal(direction, 'Product')
           defines.isSubstrateDirection = 'false';
       else
       end
    end
    assignin('base', 'defines', defines);
    
    listCompoundsIds = init__list_of_compounds();
    set(handles.cmbCompoundsIdsList,'String',listCompoundsIds);
    
    inx = 1;
    for i=1:length(listCompoundsIds)
        if strcmp(listCompoundsIds{i}(1:6), defines.initialCompound)
            inx =i;
            break;
        end    
    end
    set(handles.cmbCompoundsIdsList,'Value',inx);
    
    possibleDirection = {'Product', 'Substrate'};
    set(handles.cmbDirection,'String',possibleDirection);
    isSubstrate = defines.isSubstrateDirection;
    if isequal(isSubstrate,'true')
        set(handles.cmbDirection,'Value',2);
    else
        set(handles.cmbDirection,'Value',1);
    end

    
    maxLengthList = {'1','2','3','4','5','6','7','8','9','10'};
    set(handles.cmbMaxLength,'String',maxLengthList);
   
    ckbxVal = 0;
    if defines.isThermodinamicUsed
        ckbxVal = 1;
    end
    set(handles.isThermodinamicsUsed,'Value',ckbxVal);
    
    set(handles.minBiomassFlux,'String',defines.minBiomassFluxProportion);
    val = 'off';
    if defines.isThermodinamicUsed
        val = 'on';
    end
    set(handles.thermodinamicsValueTreshold,'Enable',val);
    
    set(handles.cmbMaxLength,'Value',str2num(defines.lengthOfBuildPathways));
    set(handles.numberOfBestPathways,'String',defines.numberOfBestPathwaysReturned);
    set(handles.thermodinamicsValueTreshold,'String',defines.thermodinamicTreshold);
    WriteToOutputTextbox(handles,hObject, 'Initialization completed!')
   
    
    set(handles.modelMenu,'ForegroundColor','r');
    set(handles.reactionsMenu,'ForegroundColor','r');
    set(handles.metabolitesMenu,'ForegroundColor','r');
    set(handles.elementsToExcludeMenu,'ForegroundColor','r');
    set(handles.thermodinamicsMenu,'ForegroundColor','r');
    set(handles.graphMenu,'ForegroundColor','r');
    set(handles.pathwaysMenu,'ForegroundColor','r');
    set(handles.resultsMenu,'ForegroundColor','r');
    set(handles.connectionMetabolitesMenu,'ForegroundColor','r');
  
    drawnow
     if evalin('base','exist(''connectionMetabolites'',''var'')')
        set(handles.connectionMetabolitesMenu,'ForegroundColor','b');
    else
        set(handles.connectionMetabolitesMenu,'ForegroundColor','r');
    end
    if evalin('base','exist(''model'',''var'')')
        set(handles.modelMenu,'ForegroundColor','b');
    else
        set(handles.modelMenu,'ForegroundColor','r');
    end
    if evalin('base','exist(''reactions'',''var'')')
        set(handles.reactionsMenu,'ForegroundColor','b');
   else
         set(handles.reactionsMenu,'ForegroundColor','r');
    end
    if evalin('base','exist(''compounds'',''var'')')
        set(handles.metabolitesMenu,'ForegroundColor','b');
     else
         set(handles.metabolitesMenu,'ForegroundColor','r');
    end
    if evalin('base','exist(''sMatrix'',''var'')')
        set(handles.graphMenu,'ForegroundColor','b');
     else
         set(handles.graphMenu,'ForegroundColor','r');
    end
    if evalin('base','exist(''elementsToExclude'',''var'')')
        set(handles.elementsToExcludeMenu,'ForegroundColor','b');
      else
         set(handles.elementsToExcludeMenu,'ForegroundColor','r');
    end
    if evalin('base','exist(''thermodinamicsValues'',''var'')')
         set(handles.thermodinamicsMenu,'ForegroundColor','b');
     else
         set(handles.thermodinamicsMenu,'ForegroundColor','r');
    end
    if evalin('base','exist(''listOfPathways'',''var'')')
        set(handles.pathwaysMenu,'ForegroundColor','b');
    else
         set(handles.pathwaysMenu,'ForegroundColor','r');
    end
    if evalin('base','exist(''analyzedPathways'',''var'')')
        set(handles.resultsMenu,'ForegroundColor','b');
     else
         set(handles.resultsMenu,'ForegroundColor','r');
    end
    guidata(hObject, handles);
    drawnow

% --- Outputs from this function are returned to the command line.
function varargout = main_OutputFcn(hObject, eventdata, handles) 
% Get default command line output from handles structure
varargout{1} = handles.output;




% --- Executes on button press in startGraphConstruction.
function startGraphConstruction_Callback(hObject, eventdata, handles)
               defines = evalin('base','defines');
               [graphNodes, graphEdges, sMatrix, statisticsData] = ...
                   start_graph_construction(defines.initialCompound,defines.lengthOfBuildPathways, 'true');

                assignin('base', 'graphNodes', graphNodes);
                assignin('base', 'graphEdges', graphEdges);
                assignin('base', 'sMatrix', sMatrix);
                assignin('base', 'statisticsData', statisticsData);

                set(handles.reactionsMenu,'ForegroundColor','b');
                set(handles.metabolitesMenu,'ForegroundColor','b');
                set(handles.graphMenu,'ForegroundColor','b');
                guidata(hObject, handles);
                drawnow update 

% --- Executes on button press in startPathwaysAnalysis.
function startPathwaysAnalysis_Callback(hObject, eventdata, handles)
                isModelLoaded = evalin('base','exist(''model'',''var'')');
                isPathwaysLoaded = evalin('base','exist(''listOfPathways'',''var'')');
                if ~isModelLoaded & ~isPathwaysLoaded
                   choice = questdlg('You should load Model and GET Pathways data first to use this function','Uncomplete data','OK','o')
                end
                if ~isModelLoaded & isPathwaysLoaded
                   choice = questdlg('You should load Model first to use this function','Uncomplete data','OK','o')
                end
                if isModelLoaded & ~isPathwaysLoaded
                   choice = questdlg('You should GET Pathways data first to use this function','Uncomplete data','OK','o')
                end

                if  isModelLoaded & isPathwaysLoaded
                    tElapsed = analyze_pathways();
                    assignin('base', 'tElapsedAnalyzis', tElapsed);
                    if evalin('base','exist(''arrayOfAllPathwaysWeights'',''var'')');
                        set(handles.resultsMenu,'ForegroundColor','b');
                        guidata(hObject,handles);
                        WriteToOutputTextbox(handles,hObject, 'Results data is loaded!' )
                    else
                        WriteToOutputTextbox(handles,hObject, 'Error! Results data is not loaded!' )
                    end
                end

% --- Executes on button press in startSearchPathways.
function startSearchPathways_Callback(hObject, eventdata, handles)
            isModelLoaded = evalin('base','exist(''model'',''var'')');
            isGraphLoaded = evalin('base','exist(''sMatrix'',''var'')');
            if ~isModelLoaded & ~isGraphLoaded
               choice = questdlg('You should load Model and Graph data first to use this function','Uncomplete data','OK','o')
            end
            if ~isModelLoaded & isGraphLoaded
               choice = questdlg('You should load Model first to use this function','Uncomplete data','OK','o')
            end
            if isModelLoaded & ~isGraphLoaded
               choice = questdlg('You should load Graph data first to use this function','Uncomplete data','OK','o')
            end

            if  isModelLoaded & isGraphLoaded
                [listOfPathways,tElapsedMain] = get_all_pathways2();
                pathaysLength = length(listOfPathways);
                assignin('base', 'listOfPathways', listOfPathways); 
                clear listOfPathways;
                set(handles.pathwaysMenu,'ForegroundColor','b');
                guidata(hObject,handles);
                WriteToOutputTextbox(handles,hObject, 'Pathways data is loaded!' )
            end

        guidata(hObject, handles);


% --- Executes on button press in loadReactions.
function loadReactions_Callback(hObject, eventdata, handles)
                [FileName,PathName,FilterIndex] = uigetfile({'*.mat','Reactions MAT File (*.mat)'}, ...
                                                                'Open Reactions Data file', '.mat');
                filePath = strcat(PathName,FileName);
                if ~isempty(filePath)
                    load(filePath);
                    if exist('reactions','var')
                        set(handles.reactionsMenu,'ForegroundColor','b');
                        assignin('base', 'reactions', reactions);
                        guidata(hObject,handles);
                        clear reactions;
                        WriteToOutputTextbox(handles,hObject, ...
                            ['Reactions data is loaded! Reactions count: ' num2str(length(reactions))] )
                     else
                        WriteToOutputTextbox(handles,hObject, ...
                        ['Reactions data is not loaded! It does not contains reactions variable'])
                    end
                else
                     set(handles.reactionsMenu,'ForegroundColor','r');
                end
                guidata(hObject, handles);
                drawnow update 
    
% --- Executes on button press in saveReactions.
function saveReactions_Callback(hObject, eventdata, handles)
                if evalin('base','exist(''reactions'',''var'')')
                   reactions=evalin('base','reactions');

                   [FileName,PathName,FilterIndex] = uiputfile({'reactions.mat','Reactions MAT File (*.mat)'}, ...
                                                                'Save Reactions Data file','reactions.mat');
                    filePath = strcat(PathName,FileName);
                    if ~isempty(filePath) 
                        save(filePath,'reactions');
                        WriteToOutputTextbox(handles,hObject, 'Reactions data is saved to harddrive! You can load it later')
                     else
                        WriteToOutputTextbox(handles,hObject, 'Reactions data is not saved! Try again!')
                    end
                    clear reactions
                end
    guidata(hObject, handles);
    drawnow update   
    
% --- Executes on button press in clearReactions.
function clearReactions_Callback(hObject, eventdata, handles)
                if evalin('base','exist(''reactions'',''var'')')
                    evalin('base',['clear ','reactions']) 
                    guidata(hObject,handles);
                    set(handles.reactionsMenu,'ForegroundColor','r');
                    WriteToOutputTextbox(handles,hObject, 'Reactions data is cleared!')
                end
    guidata(hObject, handles);
    drawnow update  
    
function loadMetabolites_Callback(hObject, eventdata, handles)
            [FileName,PathName,FilterIndex] = uigetfile({'*.mat','Metabolites MAT File (*.mat)'}, ...
                                                            'Open Metabolites Data file', '*.mat');
             filePath = strcat(PathName,FileName);
             if ~isempty(filePath) 
                load(filePath);
                if exist('metabolites','var')
                    assignin('base', 'metabolites', metabolites);
                    set(handles.metabolitesMenu,'ForegroundColor','b');
                    guidata(hObject,handles);
                    clear metabolites;
                    WriteToOutputTextbox(handles,hObject, ...
                        ['Metabolites data is loaded! Metabolites count: ' num2str(length(metabolites))] )
                else
                    WriteToOutputTextbox(handles,hObject, ...
                    ['Metabolites data is not loaded! It does not contains metabolites variable'])
                end
            else
                 set(handles.metabolitesMenu,'ForegroundColor','r');
             end
               guidata(hObject, handles);
            drawnow update
    
    
% --------------------------------------------------------------------
function loadGraphData_Callback(hObject, eventdata, handles)
 [FileName,PathName,FilterIndex] = uigetfile({'*.mat','sMatrix MAT File (*.mat)'}, ...
                                                    'Open Graph Data file', '.mat');
    filePath = strcat(PathName,FileName);
    if ~isempty(filePath)
        load(filePath);
        if exist('sMatrix','var')
            set(handles.graphMenu,'ForegroundColor','b');
            
            assignin('base', 'graphNodes', graphNodes);
            assignin('base', 'graphEdges', graphEdges);
            assignin('base', 'sMatrix', sMatrix);
            guidata(hObject,handles);
            clear sMatrix;
            WriteToOutputTextbox(handles,hObject, 'Graph data is loaded!' )
         else
            WriteToOutputTextbox(handles,hObject, ...
            ['Graph data is not loaded! It does not contains Graph variable'])
        end
    else
         set(handles.graphMenu,'ForegroundColor','r');
    end
    guidata(hObject, handles);
    drawnow update 
    
% --------------------------------------------------------------------
function saveGraphData_Callback(hObject, eventdata, handles)
             if evalin('base','exist(''sMatrix'',''var'')')
                   sMatrix=evalin('base','sMatrix');

                   [FileName,PathName,FilterIndex] = uiputfile({'sMatrix.mat','sMatrix MAT File (*.mat)'}, ...
                                                                'Save Graph Data file','sMatrix.mat');
                    filePath = strcat(PathName,FileName);
                    if ~isempty(filePath) 
                        save(filePath,'sMatrix', 'graphNodes', 'graphEdges');
                        WriteToOutputTextbox(handles,hObject, 'Graph data is saved to harddrive! You can load it later')
                     else
                        WriteToOutputTextbox(handles,hObject, 'Graph data is not saved! Try again!')
                    end
                    clear reactions
                end
    guidata(hObject, handles);
    drawnow update   
% --------------------------------------------------------------------
function clearGraphData_Callback(hObject, eventdata, handles)
                 if evalin('base','exist(''sMatrix'',''var'')')
                        evalin('base',['clear ','sMatrix']) 
                        evalin('base',['clear ','graphEdges']) 
                        evalin('base',['clear ','graphNodes']) 
                        guidata(hObject,handles);
                        set(handles.graphMenu,'ForegroundColor','r');
                        WriteToOutputTextbox(handles,hObject, 'Graph data is cleared!')
                    end
    guidata(hObject, handles);
    drawnow update  


% --------------------------------------------------------------------
            function loadMATFile_Callback(hObject, eventdata, handles)
             [FileName,PathName,FilterIndex] = uigetfile({'*.mat','Model MAT File (*.mat)'}, ...
                                                                'Open Model Data file', '*.mat');
                filePath = strcat(PathName,FileName);
                try
                     if ~isempty(filePath) 
                        WriteToOutputTextbox(handles,hObject, 'Starting Cobra initialization')
                        WriteToOutputTextbox(handles,hObject, ...
                                 'This can take a while ... Locking controls ' );
                        LockGUIControls(handles,hObject, 'off')
                        initCobraToolbox;

                        WriteToOutputTextbox(handles,hObject, 'Cobra is initialized')
                        WriteToOutputTextbox(handles,hObject, 'Reading model file')

                        load(filePath)

                        if exist('model','var')

                            WriteToOutputTextbox(handles,hObject, ...
                                'Model is loaded! Starting filling model with KEGG IDs' )
                            drawnow

                            model = CheckMOdelToKEGGData(model);

                            LockGUIControls(handles,hObject, 'on')
                            set(handles.modelMenu,'ForegroundColor','b');

                            assignin('base', 'model', model);
                            guidata(hObject, handles);
                            clear model;
                            WriteToOutputTextbox(handles,hObject, ...
                                'Model is ready!' )
                        else
                            LockGUIControls(handles,hObject, 'on')
                            WriteToOutputTextbox(handles,hObject, ...
                            ['Model is not loaded! File does not contains model'])
                        end
                    else
                         set(handles.modelMenu,'ForegroundColor','r');
                    end
                catch err
                     disp(err);
                     LockGUIControls(handles,hObject, 'on')
                end
               guidata(hObject, handles);
               drawnow update

% --------------------------------------------------------------------
function saveModelFile_Callback(hObject, eventdata, handles)
                 if evalin('base','exist(''model'',''var'')')

                   model = evalin('base','model');

                   [FileName,PathName,FilterIndex] = uiputfile({'*.mat','Model MAT File (*.mat)'}, ...
                                                                'Save Model Data file','*.mat');
                    filePath = strcat(PathName, FileName);
                    if ~isempty(filePath)
                        save(filePath,'model');
                        clear model;
                        WriteToOutputTextbox(handles,hObject, 'Model data is saved to harddrive! You can load it later')
                     else
                        WriteToOutputTextbox(handles,hObject, 'Model data is not saved! Try again!')
                     end
                end
  guidata(hObject, handles);
    drawnow update

% --------------------------------------------------------------------
function clearModelFile_Callback(hObject, eventdata, handles)
               if evalin('base','exist(''model'',''var'')')
                   evalin('base',['clear ','model']);
                    guidata(hObject,handles);
                    set(handles.modelMenu,'ForegroundColor','r');
                    WriteToOutputTextbox(handles,hObject, 'Model data is cleared!')
                end
  guidata(hObject, handles);
  drawnow update

% --- Executes on button press in saveMetabolites.
function saveMetabolites_Callback(hObject, eventdata, handles)
                if evalin('base','metabolites'',''var'')')
                   metabolites=evalin('base',['clear ','metabolites']); 
                   [FileName,PathName,FilterIndex] = uiputfile({'*.mat','Metabolites MAT File (*.mat)'}, ...
                                                                'Save Metabolites Data file','*.mat');
                    filePath = strcat(PathName,FileName);
                    if ~isempty(filePath)
                        save(filePath,'metabolites');
                        WriteToOutputTextbox(handles,hObject, 'Metabolites data is saved to harddrive! You can load it later')
                        clear metabolites;
                    else
                        WriteToOutputTextbox(handles,hObject, 'Metabolites data is not saved! Try again!')
                     end
                end
     guidata(hObject, handles);
    drawnow update 
    
% --- Executes on button press in clearMetabolites.
function clearMetabolites_Callback(hObject, eventdata, handles)
              if evalin('base','exist(''metabolites'',''var'')')
                    evalin('base',['clear ','metabolites']);

                    set(handles.metabolitesMenu,'ForegroundColor','r');
                    WriteToOutputTextbox(handles,hObject, 'Metabolites data is cleared!')
                    guidata(hObject,handles);
              end
  guidata(hObject, handles);
  drawnow update

function loadThermodinamicsData_Callback(hObject, eventdata, handles)
         handles = loadThermodinamicsDataFunction(hObject, handles); 

            % --- Executes on button press in loadThermodinamicsData.
            function handles = loadThermodinamicsDataFunction(hObject, handles)
                [FileName,PathName,FilterIndex] = uigetfile({'*.csv;*.xls;*.xlsx','Excel Files (*.csv,*.xls,*.xlsx)'}, ...
                                                            'Open eQuilibrator Data file');
                   filePath = strcat(PathName,FileName);
                   if ~isempty(filePath) 
                        WriteToOutputTextbox(handles,hObject, ...
                                 'This can take a while ... Locking controls ' );
                        LockGUIControls(handles,hObject, 'off')
                        [ndata, text, alldata] = xlsread(filePath);
                        thermodinamicsValues=[];
                        h = waitbar(0,'Please wait... Looking for Reactions thermodinamics data');
                        for i=2:length(text)
                            waitbar(i/length(text),h, [num2str(i), ' reactions of ', num2str(length(text)), ' total' ])
                            rowValue = regexp(text(i),',','split');
                            reactionid='R00000';
                            reactionid(6-length(rowValue{1}{1}(:,:))+1:6)=rowValue{1}{1};
                            thermodinamicsValues=[thermodinamicsValues; reactionid, rowValue{1}(2)];
                        end   
                        close(h)
                        LockGUIControls(handles,hObject, 'on')
                        if ~isempty(thermodinamicsValues)
                            set(handles.thermodinamicsMenu,'ForegroundColor','b');              
                            assignin('base', 'thermodinamicsValues', thermodinamicsValues);
                            guidata(hObject, handles);

                            WriteToOutputTextbox(handles,hObject, ...
                                'Thermodinamics data is loaded!' )
                        else
                              WriteToOutputTextbox(handles,hObject, ...
                                'Thermodinamics data is not loaded!' )
                             set(handles.isThermodinamicsUsed,'Value',0);
                       set(handles.thermodinamicsValueTreshold,'Enable','off');
                        end
                   else
                       set(handles.isThermodinamicsUsed,'Value',0);
                       set(handles.thermodinamicsValueTreshold,'Enable','off');
                   end
                guidata(hObject, handles);
                drawnow update
    
% --- Executes on button press in clearThermodinamicsData.
function clearThermodinamicsData_Callback(hObject, eventdata, handles)
                if  evalin('base','exist(''thermodinamicsValues'',''var'')')
                    evalin('base',['clear ','thermodinamicsValues']);
                    set(handles.thermodinamicsMenu,'ForegroundColor','r');
                    WriteToOutputTextbox(handles,hObject, 'Thermodinamics data is cleared!')
                    set(handles.isThermodinamicsUsed,'Value',0);
                    set(handles.thermodinamicsValueTreshold,'Enable','off');
                    guidata(hObject,handles);
                end
              guidata(hObject, handles);
              drawnow update


function loadElementsToExclude_Callback(hObject, eventdata, handles)
                  WriteToOutputTextbox(handles,hObject, 'Loading Elements-to-exclude!')
                  elementsToExclude = textread('listOfMeabolitesToExclude.txt', '%s', 'whitespace', ' ');   

                   if ~isempty(elementsToExclude)
                          set(handles.elementsToExcludeMenu,'ForegroundColor','b');
                          assignin('base', 'elementsToExclude', elementsToExclude);
                          guidata(hObject, handles);
                          clear elementsToExclude;
                   else
                          WriteToOutputTextbox(handles,hObject, 'Elements-to-exclude are not loaded!')
                   end
               guidata(hObject, handles);
               drawnow update
    
% --- Executes on button press in clearElementsToExclude.
function clearElementsToExclude_Callback(hObject, eventdata, handles)
            clearElementsToExcludeFunction(hObject, handles)

function handles = clearElementsToExcludeFunction(hObject, handles)
             if  evalin('base','exist(''elementsToExclude'',''var'')')
                   evalin('base',['clear ','elementsToExclude']);
                    set(handles.elementsToExcludeMenu,'ForegroundColor','r');
                    WriteToOutputTextbox(handles,hObject, 'Elements-to-exlude data is cleared!')
                    guidata(hObject,handles);
             end
                guidata(hObject, handles);
                drawnow update  

                
                
                
% --- Executes on selection change in cmbCompoundsIdsList.
function cmbCompoundsIdsList_Callback(hObject, eventdata, handles)
    contents = cellstr(get(hObject,'String'));
    values = regexp(contents{get(hObject,'Value')},'C.....', 'match');  
    defines = evalin('base','defines');
    defines.initialCompound = values{1};
    assignin('base', 'defines', defines);
    guidata(hObject, handles);
    
    
    

% --- Executes on button press in isThermodinamicsUsed.
function isThermodinamicsUsed_Callback(hObject, eventdata, handles)
    isDataLoaded = get(handles.thermodinamicsMenu,'ForegroundColor');
    if get(hObject,'Value')
         if(isDataLoaded == [1 0 0])
             choice = questdlg('You should load thermodinamics data to use this function','Load thermodinamics','Load','Cancel','o')
             if strcmp(choice,'Load')
                set(handles.thermodinamicsValueTreshold,'Enable','on');
                handles = loadThermodinamicsDataFunction(hObject, handles);
             else
                set(handles.isThermodinamicsUsed,'Value',0);
                set(handles.thermodinamicsValueTreshold,'Enable','off');
             end
         else
             set(handles.thermodinamicsValueTreshold,'Enable','on');
         end
    else
         set(handles.thermodinamicsValueTreshold,'Enable','off');
    end
    isTrue = 'false';
    if get(hObject,'Value')
        isTrue = 'true';
    end
    defines=evalin('base','defines');
    defines.isThermodinamicUsed = isTrue;
    assignin('base', 'defines', defines);
guidata(hObject, handles);   





function minBiomassFlux_Callback(hObject, eventdata, handles)
    minBiomass = str2double(get(hObject,'String'));
    if isempty(minBiomass) | isnan(minBiomass)
        h = warndlg('Min Biomass Input contains disallowed symbols! You shpuld correct it. Othwerwise it will be ignored and default value 0.2 will be used');
    else
        defines=evalin('base','defines');
        defines.minBiomassFluxProportion = num2str(minBiomass);
        assignin('base', 'defines', defines);
    end
    guidata(hObject, handles); 
    
    
    
    

 function numberOfBestPathways_Callback(hObject, eventdata, handles)
    pathways = str2double(get(hObject,'String'))
    if isempty(pathways) | isnan(pathways)
        h = warndlg('Number of returned pathways contains disallowed symbols! You shpuld correct it. Othwerwise it will be ignored and default value 500 will be used');
    else
        defines = evalin('base','defines');
        defines.numberOfBestPathwaysReturned = num2str(pathways);
        assignin('base', 'defines', defines);
    end
    guidata(hObject, handles); 
    
    
    
    
function thermodinamicsValueTreshold_Callback(hObject, eventdata, handles)
    treshold = str2double(get(hObject,'String'))
    if isempty(treshold) | isnan(treshold)
        h = warndlg('Thermodinamics treshold contains disallowed symbols! You shpuld correct it. Othwerwise it will be ignored and default value 5 will be used');
    else
        defines = evalin('base','defines');
        defines.thermodinamicTreshold = num2str(treshold);
        assignin('base', 'defines', defines);
    end
    guidata(hObject, handles); 

    
    
    

% --- Executes on selection change in cmbMaxLength.
function cmbMaxLength_Callback(hObject, eventdata, handles)
    contents = cellstr(get(hObject,'String'));
    defines = evalin('base','defines');
    defines.lengthOfBuildPathways = contents{get(hObject,'Value')};
    assignin('base', 'defines', defines);
    guidata(hObject, handles);
    
    
    

  
% --- Executes on selection change in cmbDirection.
function cmbDirection_Callback(hObject, eventdata, handles)
    contents = cellstr(get(hObject,'String'));
    isSubstrateDirection = 'false';
    if isequal(contents{get(hObject,'Value')},'Substrate')
        isSubstrateDirection = 'true';
    end
    defines = evalin('base','defines');   
    defines.isSubstrateDirection = isSubstrateDirection;
    assignin('base', 'defines', defines);
    
guidata(hObject, handles);





% --- Executes on button press in loadedThermodinamics.
function loadedThermodinamics_Callback(hObject, eventdata, handles)
% --- Executes on button press in loadedElementsToExclude.
function loadedElementsToExclude_Callback(hObject, eventdata, handles)
% --- Executes on button press in loadedGraph.
function loadedGraph_Callback(hObject, eventdata, handles)
% --- Executes on button press in loadedMetabolites.
function loadedMetabolites_Callback(hObject, eventdata, handles)
% --- Executes on button press in loadedReactions.
function loadedReactions_Callback(hObject, eventdata, handles)
% --- Executes on button press in loadedModel.
function loadedModel_Callback(hObject, eventdata, handles)
% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
% --- Executes during object creation, after setting all properties.
function cmbDirection_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function cmbMaxLength_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function minBiomassFlux_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function cmbCompoundsIdsList_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
function OutputTextbox_Callback(hObject, eventdata, handles)
% --- Executes during object creation, after setting all properties.
function OutputTextbox_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'ForegroundColor'), get(0,'defaultUicontrolForegroundColor'))
    set(hObject,'ForegroundColor','white');
end
function edit1_Callback(hObject, eventdata, handles)
function edit1_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
% --- Executes on key press with focus on minBiomassFlux and none of its controls.
function minBiomassFlux_KeyPressFcn(hObject, eventdata, handles)
% --- Executes during object creation, after setting all properties.
function numberOfBestPathways_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function thermodinamicsValueTreshold_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
% --------------------------------------------------------------------
function resultsMenu_Callback(hObject, eventdata, handles)
% --------------------------------------------------------------------
function thermodinamicsMenu_Callback(hObject, eventdata, handles)
% --------------------------------------------------------------------
function modelMenu_Callback(hObject, eventdata, handles)
% --------------------------------------------------------------------
function reactionsMenu_Callback(hObject, eventdata, handles)
% --------------------------------------------------------------------
function metabolitesMenu_Callback(hObject, eventdata, handles)
% --------------------------------------------------------------------
function graphMenu_Callback(hObject, eventdata, handles)
% --------------------------------------------------------------------
function elementsToExcludeMenu_Callback(hObject, eventdata, handles)
% --------------------------------------------------------------------
function uipanel6_ButtonDownFcn(hObject, eventdata, handles)
% --- Executes on button press in readyToFindPathways.
function readyToFindPathways_Callback(hObject, eventdata, handles)
% --- Executes on button press in readyToStartAnalysis.
function readyToStartAnalysis_Callback(hObject, eventdata, handles)
% --- Executes on button press in readyToStartGraph.
function readyToStartGraph_Callback(hObject, eventdata, handles)
% --- Executes on button press in loadedPathways.
function loadedPathways_Callback(hObject, eventdata, handles)
% --- Executes on button press in loadedResults.
function loadedResults_Callback(hObject, eventdata, handles)
% --------------------------------------------------------------------
function pathwaysMenu_Callback(hObject, eventdata, handles)
    
function LockGUIControls(handles,hObject, onOrOff)
    set(handles.loadReactions,'Enable',onOrOff)
    set(handles.loadMetabolites,'Enable',onOrOff)
    set(handles.saveMetabolites,'Enable',onOrOff)
    set(handles.clearMetabolites,'Enable',onOrOff)
    set(handles.saveReactions,'Enable',onOrOff)
    set(handles.clearReactions,'Enable',onOrOff) 
    set(handles.loadElementsToExclude,'Enable',onOrOff)
    set(handles.clearElementsToExclude,'Enable',onOrOff)
    set(handles.loadThermodinamicsData,'Enable',onOrOff)
    set(handles.clearThermodinamicsData,'Enable',onOrOff)
    set(handles.startGraphConstruction,'Enable',onOrOff)
    set(handles.startSearchPathways,'Enable',onOrOff)
    set(handles.startPathwaysAnalysis,'Enable',onOrOff)
    set(handles.cmbCompoundsIdsList,'Enable',onOrOff)
    set(handles.cmbDirection,'Enable',onOrOff)
    set(handles.cmbMaxLength,'Enable',onOrOff)
    set(handles.minBiomassFlux,'Enable',onOrOff)
    set(handles.automaticModeButton,'Enable',onOrOff)
    set(handles.isThermodinamicsUsed,'Enable',onOrOff)
    set(handles.numberOfBestPathways,'Enable',onOrOff)
    set(handles.thermodinamicsValueTreshold,'Enable',onOrOff)
    set(handles.modelMenu,'Enable',onOrOff)
    set(handles.reactionsMenu,'Enable',onOrOff)
    set(handles.metabolitesMenu,'Enable',onOrOff)
    set(handles.graphMenu,'Enable',onOrOff)
    set(handles.elementsToExcludeMenu,'Enable',onOrOff)
    set(handles.thermodinamicsMenu,'Enable',onOrOff)
    set(handles.resultsMenu,'Enable',onOrOff)
    set(handles.pushbutton40,'Enable',onOrOff)
    
    guidata(hObject,handles);
    drawnow


function WriteToOutputTextbox(handles,hObject, text)
        outtext = get(handles.OutputTextbox,'String')
            if ~isempty(outtext)
                [row, col] = size(outtext);
                if row > 100
                   outtext(101,:) = [];
                end
            end
            outtext = {strcat('# ',text); outtext};
            set(handles.OutputTextbox, 'String', char(outtext));
            guidata(hObject, handles);
            drawnow update



% --------------------------------------------------------------------
function loadXMLFile_Callback(hObject, eventdata, handles)
                 [FileName,PathName,FilterIndex] = uigetfile({'*.xml','Model SBML File (*.xml)'}, ...
                                                                    'Open Model Data file', '*.xml');
                     filePath = strcat(PathName,FileName);
                     try
                         if ~isempty(filePath) 
                            WriteToOutputTextbox(handles,hObject, 'Starting Cobra initialization')
                            WriteToOutputTextbox(handles,hObject, ...
                                     'This can take a while ... Locking controls ' );

                            LockGUIControls(handles,hObject, 'off')

                            initCobraToolbox;

                            WriteToOutputTextbox(handles,hObject, 'Cobra is initialized')
                            WriteToOutputTextbox(handles,hObject, 'Reading model file')

                            model = readCbModel(filePath)

                            if exist('model','var')
                                WriteToOutputTextbox(handles,hObject, ...
                                    'Model is loaded! Starting filling model with KEGG IDs' )

                                model = CheckMOdelToKEGGData(model);

                                LockGUIControls(handles,hObject, 'on')

                                set(handles.modelMenu,'ForegroundColor','b');
                                assignin('base', 'model', model);

                                guidata(hObject, handles);

                                WriteToOutputTextbox(handles,hObject, ...
                                    'Model is ready!' )
                                clear model;
                            else
                                LockGUIControls(handles,hObject, 'on')
                                WriteToOutputTextbox(handles,hObject, ...
                                ['Model is not loaded! File does not contains model'])
                            end
                        else
                             set(handles.modelMenu,'ForegroundColor','r');
                         end
                     catch err
                         disp(err);
                         LockGUIControls(handles,hObject, 'on')
                    end
    guidata(hObject, handles);
    drawnow update

function model = CheckMOdelToKEGGData(model)
                    metKEGGID = model.metKEGGID;
                    emptyKEGGID = 0;
                    for i = 1:length(metKEGGID)
                        if ~isempty(metKEGGID{i})
                           metaboliteKEGGIDs_KEGGID(i) = cellstr(metKEGGID{i});
                        else
                            emptyKEGGID = emptyKEGGID + 1;
                        end
                    end   
                    percentEmptyKEGGID = emptyKEGGID * 100 / length(metKEGGID);
                    choice = questdlg(['In model are ', num2str(percentEmptyKEGGID), ...
                        '% empty KEGGIDs. Do you want to try to fill model with KEGGIDs?'], ...
                        'Load KEGGIDs','Fill','No','o')
                    if strcmp(choice,'Fill')
                        model = init_model(model);
                    end

    
% --------------------------------------------------------------------
function editElementsToExclude_Callback(hObject, eventdata, handles)
                msgbox('You should to reload data afterwards');
                open('datfiles/listOfMeabolitesToExclude.txt');
                handles = clearElementsToExcludeFunction(hObject, handles)
                guidata(hObject, handles);
                drawnow update


% --------------------------------------------------------------------
function loadPathwaysData_Callback(hObject, eventdata, handles)
   [FileName,PathName,FilterIndex] = uigetfile({'*.mat','Pathways MAT File (*.mat)'}, ...
                                                    'Open Pathways Data file', '.mat');
    filePath = strcat(PathName,FileName);
    if ~isempty(filePath)
        load(filePath);
        if exist('listOfPathways','var')
            set(handles.pathwaysMenu,'ForegroundColor','b');
            pathaysLength = length(listOfPathways);
            
            assignin('base', 'listOfPathways', listOfPathways);
            guidata(hObject,handles);
            clear listOfPathways;
            WriteToOutputTextbox(handles,hObject, 'Pathways data is loaded!' )
         else
            WriteToOutputTextbox(handles,hObject, ...
            ['Pathways data is not loaded! It does not contains List of Pathways variable'])
        end
    else
         set(handles.pathwaysMenu,'ForegroundColor','r');
    end
    guidata(hObject, handles);
    drawnow update 

% --------------------------------------------------------------------
function savePathwaysData_Callback(hObject, eventdata, handles)
                    if evalin('base','exist(''listOfPathways'',''var'')')
                       listOfPathways = evalin('base','listOfPathways');

                       [FileName,PathName,FilterIndex] = uiputfile({'listOfPathways.mat','Pathways MAT File (*.mat)'}, ...
                                                                    'Save Pathways Data file','listOfPathways.mat');
                        filePath = strcat(PathName,FileName);
                        if ~isempty(filePath)
                            save(filePath,'listOfPathways');
                            WriteToOutputTextbox(handles,hObject, 'Pathways data is saved to harddrive! You can load it later')
                         else
                            WriteToOutputTextbox(handles,hObject, 'Pathways data is not saved! Try again!')
                        end
                        clear listOfPathways
                    end
    guidata(hObject, handles);
    drawnow update   
    
% --------------------------------------------------------------------
function clearPathwaysData_Callback(hObject, eventdata, handles)
    if evalin('base','exist(''listOfPathways'',''var'')')
        evalin('base',['clear ','listOfPathways']) 
        set(handles.pathwaysMenu,'ForegroundColor','r');
        WriteToOutputTextbox(handles,hObject, 'Pathways data is cleared!')
        guidata(hObject,handles);
    end
    guidata(hObject, handles);
    drawnow update  
% --------------------------------------------------------------------


% --------------------------------------------------------------------
function saveResultsData_Callback(hObject, eventdata, handles)
% hObject    handle to saveResultsData (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
                 if evalin('base','exist(''analyzedPathways'',''var'')')
                       analyzedPathways = evalin('base','analyzedPathways');
                        arrayOfAllPathwaysWeights = evalin('base','arrayOfAllPathwaysWeights');

                       [FileName,PathName,FilterIndex] = uiputfile({'analyzesResults.mat','Results MAT File (*.mat)'}, ...
                                                                    'Save Results Data file','analyzesResults.mat');
                        filePath = strcat(PathName,FileName);
                        if ~isempty(filePath) 
                            save(filePath,'analyzesResults', 'arrayOfAllPathwaysWeights');
                            WriteToOutputTextbox(handles,hObject, 'Results data is saved to harddrive! You can load it later')
                         else
                            WriteToOutputTextbox(handles,hObject, 'Results data is not saved! Try again!')
                        end
                        clear arrayOfAllPathwaysWeights
                        clear analyzedPathways
                    end
    guidata(hObject, handles);
    drawnow update   

% --------------------------------------------------------------------
function clearResultsData_Callback(hObject, eventdata, handles)
% hObject    handle to clearResultsData (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
              if evalin('base','exist(''analyzedPathways'',''var'')')
                    evalin('base',['clear ','analyzedPathways']) 
                    evalin('base',['clear ','arrayOfAllPathwaysWeights']) 
                    set(handles.resultsMenu,'ForegroundColor','r');
                    WriteToOutputTextbox(handles,hObject, 'Results data is cleared!')
                    guidata(hObject,handles);
              end

 drawnow update  

% --- Executes on button press in pushbutton40.
function pushbutton40_Callback(hObject, eventdata, handles)
            if evalin('base','exist(''analyzedPathways'',''var'')')
               initCobraToolbox
               untitled
            end
        

function edit8_Callback(hObject, eventdata, handles)
% hObject    handle to edit8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit8 as text
%        str2double(get(hObject,'String')) returns contents of edit8 as a double


% --- Executes during object creation, after setting all properties.
function edit8_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton41.
function pushbutton41_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton41 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 disp('Getting working dirrectory.. ');
    dname = uigetdir;
    set(handles.edit8, 'string', dname);
    assignin('base', 'dname', dname);


% --- Executes on button press in pushbutton42.
function automaticModeButton_Callback(hObject, eventdata, handles)

  LockGUIControls(handles,hObject, 'off')
                  defines = evalin('base','defines');

                  %%TODO CHECK FOR NULL VALUES

                   [graphNodes, graphEdges, sMatrix, statisticsData] = ...
                       start_graph_construction(defines.initialCompound,defines.lengthOfBuildPathways, 'true');
                    assignin('base', 'graphNodes', graphNodes);
                    assignin('base', 'graphEdges', graphEdges);
                    assignin('base', 'sMatrix', sMatrix);
                    assignin('base', 'statisticsData', statisticsData);

                    clear graphNodes;
                    clear graphEdges;
                    clear sMatrix;   
                    clear statisticsData;

                    set(handles.reactionsMenu,'ForegroundColor','b');
                    set(handles.metabolitesMenu,'ForegroundColor','b');
                    set(handles.graphMenu,'ForegroundColor','b');
                       guidata(hObject,handles)

                        [listOfPathways,tElapsedMain] = get_all_pathways2();
                        assignin('base', 'listOfPathways', listOfPathways); 
                        pathaysLength = length(listOfPathways);

                        assignin('base', 'tElapsed_PathwaysSearch', tElapsedMain);
                        clear listOfPathways;
                        set(handles.pathwaysMenu,'ForegroundColor','b');
                        guidata(hObject,handles);
                        WriteToOutputTextbox(handles,hObject, 'Pathways data is loaded!' )


                        [tElapsed] = analyze_pathways();
                        assignin('base', 'tElapsedAnalyzis', tElapsed);
                        if exist('arrayOfAllPathwaysWeights','var')
                            set(handles.resultsMenu,'ForegroundColor','b');
                            guidata(hObject,handles);
                            WriteToOutputTextbox(handles,hObject, 'Results data is loaded!' )
                        else
                            WriteToOutputTextbox(handles,hObject, 'Error! Results data is not loaded!' )
                        end
                     LockGUIControls(handles,hObject, 'on')


% --------------------------------------------------------------------
function connectionMetabolitesMenu_Callback(hObject, eventdata, handles)
% hObject    handle to connectionMetabolitesMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function loadConnectionMetabolites_Callback(hObject, eventdata, handles)
    WriteToOutputTextbox(handles,hObject, 'Loading connection metabolites!')
      connectionMetabolites = textread('datfiles/connectionMetabolites.txt', '%s', 'whitespace', ' ');   

       if ~isempty(connectionMetabolites)
              set(handles.connectionMetabolitesMenu,'ForegroundColor','b');
              assignin('base', 'connectionMetabolites', connectionMetabolites);
              guidata(hObject, handles);
              clear connectionMetabolites;
       else
              WriteToOutputTextbox(handles,hObject, 'Connection metabolites are not loaded!')
       end
   guidata(hObject, handles);
   drawnow update

% --------------------------------------------------------------------
function clearConnectionMetabolites_Callback(hObject, eventdata, handles)
clearConnectionMetabolitesFunction(hObject, handles)

% --------------------------------------------------------------------
function editConnectionMetabolites_Callback(hObject, eventdata, handles)
    msgbox('You should to reload data afterwards');
    open('datfiles/connectionMetabolites.txt');
    handles = clearConnectionMetabolitesFunction(hObject, handles)
    guidata(hObject, handles);
    drawnow update

function handles = clearConnectionMetabolitesFunction(hObject, handles)
 if  evalin('base','exist(''connectionMetabolites'',''var'')')
       evalin('base',['clear ','connectionMetabolites']);
        set(handles.connectionMetabolitesMenu,'ForegroundColor','r');
        WriteToOutputTextbox(handles,hObject, 'Connection metabolites data is cleared!')
        guidata(hObject,handles);
 end
    guidata(hObject, handles);
    drawnow update  

% --------------------------------------------------------------------
function Untitled_1_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)



function numberOfBestPathways_Callback(hObject, eventdata, handles)
% hObject    handle to numberOfBestPathways (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of numberOfBestPathways as text
%        str2double(get(hObject,'String')) returns contents of numberOfBestPathways as a double
